<script setup>
import {ref} from 'vue';
import Header from './components/Header.vue';
import ImageUploader from './components/ImageUploader.vue';
import AnalysisResult from './components/AnalysisResult.vue';
import NutritionDisplay from './components/NutritionDisplay.vue';
import LoadingSpinner from './components/LoadingSpinner.vue';
import ErrorMessage from './components/ErrorMessage.vue';
import {analyzeFood} from './services/api';

const nutritionData = ref({});
const recommendations = ref([]);
const loading = ref(false);
const error = ref('');
const resultImageUrl = ref('');

const handleImageSelected = async (file) => {
  try {
    loading.value = true;
    error.value = '';

    const result = await analyzeFood(file);
    resultImageUrl.value = result.imageUrl;
    nutritionData.value = result;
    recommendations.value = result.recommendations;
  } catch (err) {
    error.value = 'Error analyzing the image. Please try again.';
    console.error(err);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <Header/>

    <main class="max-w-6xl mx-auto py-8 px-4">
      <!-- Upload and Analysis Result side by side -->
      <div class="grid md:grid-cols-2 gap-6 mb-8">
        <ImageUploader @image-selected="handleImageSelected"/>

        <div class="relative">
          <LoadingSpinner
              v-if="loading"
              message="正在分析你的食物..."
              class="absolute inset-0 z-10 bg-white bg-opacity-90 flex items-center justify-center"
          />

          <ErrorMessage
              v-if="error"
              :message="error"
              class="absolute inset-0 z-10 flex items-center justify-center"
          />

          <AnalysisResult :image-url="resultImageUrl"/>
        </div>

      </div>

      <!-- Nutrition Facts and Recommendations -->
      <NutritionDisplay
          v-if="nutritionData.dict"
          :nutrition-data="nutritionData"
          :recommendations="recommendations"
      />
    </main>
  </div>
</template>